/**
思路是：1、求出树高
        2、用性质求出倒数第二层以上的结点数
        3、二分求出最后一层的结点数。
        4、相加起来就可以了
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 *lc222:https://leetcode.cn/problems/count-complete-tree-nodes/
 */

class Solution {
public:
    //求树高
    int countlevel(TreeNode* root){
        int count = 0;
        while(root){
            root = root->left;
            count++;
        }
        return count;
    }
    bool is_exist(TreeNode* root,int index, int depth){
        TreeNode* node = root;

        while(depth){
            //最后一层分界线
            int mid = ((1<<depth)>>1);
            if(index > mid){
                //说明在右子树
                index -=mid;
                node = node->right;
            }
            else{
                node = node->left;
            }
            depth--;
        }
        return node != nullptr;
    }

    int countNodes(TreeNode* root) {
        if (root == nullptr) return 0;
        int depth = countlevel(root); //树高
        int depth_prev = depth - 1;  //倒数第二层
        int start = 1, end = (1 << depth_prev),mid = 0;//倒数第二层的结点
        while(start <= end){
            mid = start + ((end - start)>>1);
            cout << mid<<" ";
            if(is_exist(root,mid,depth_prev)){start = mid + 1;}
            else {
                end = mid - 1;
            }
        }
        return (1<<depth_prev) -1 + start - 1;
    }
};